<!DOCTYPE html>
<html>
<head>
	<title>Backbone Underscore Example</title>
	<link href="/PersonInventory/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
	<div class="container">
		<h2>User Manager</h2>
		<hr />
		<div class="page"></div>
	</div>
	
	<script type="text/template" id="user-list-template">
		<a href="#/new" class="btn btn-primary">New User</a>
		<hr/> 
		<table class="table table-bordered">
			<thead>
				<tr>
					<th>First Name</th>
					<th>Last Name</th>
					<th>Age</th>
					<th>Gender</th>
					<th></th>
				</tr>
			</thead>
			<tbody>
				<% _.each(users, function(user) { %>
					<tr>
						<td><%=user.get("firstName") %></td>
						<td><%=user.get("lastName") %></td>
						<td><%=user.get("age") %></td>
						<td><%=user.get("gender") %></td>
						<td><a href="#/edit/<%= user.id %>" class="btn">Edit</a></td>
						<td><a href="#/delete/<%= user.id %>" class="btn btn-danger delete">Delete</a></td>
					</tr>
				<%}); %>
			</tbody>
		</table>
	</script>
	
	<script type="text/template" id="save-list-template">
		<form class="edit-user-form">
			<legend><%= user ? 'Update' : 'Create' %> User</legend>

			<label>First Name</label>
			<input type="text" name="firstName" value='<%= user ? user.get('firstName') : '' %>'/>
			
			<label>Last Name</label>
			<input type="text" name="lastName" value='<%= user ? user.get('lastName') : '' %>'/>
			
			<label>Age</label>
			<input type="text" name="age" value='<%= user ? user.get('age') : '' %>'/>
			
			<label>Gender</label>
			<input type="text" name="gender" value='<%= user ? user.get('gender') : '' %>'/>
			
			<hr/>
			
			<% if(user) { %>
				<input type="hidden" name="id" value="<%= user.id %>" />
			<% } %>			

			<button type="submit" class="btn btn-primary"><%= user ? 'Update' : 'Create' %></button>
		</form>
	</script>
	
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>    
    <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
    <script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
	<script>

		//To be used in case of remote server rest calls. Always needed
		//commented as client and server is on dev machine
		//$.ajaxPrefilter(function (options, originalOptions, jqXHR){
		//	options.url = 'http://localhost:8080' + options.url;			
		//});
		
		$.fn.serializeObject = function() {
		    var o = {};
		    var a = this.serializeArray();
		    $.each(a, function() {
		        if (o[this.name] !== undefined) {
		            if (!o[this.name].push) {
		                o[this.name] = [o[this.name]];
		            }
		            o[this.name].push(this.value || '');
		        } else {
		            o[this.name] = this.value || '';
		        }
		    });
		    return o;
		};
	
		var Users = Backbone.Collection.extend({
			url:'/PersonInventory/rest/person/get'
		});
		
		var User = Backbone.Model.extend({
			urlRoot:'/PersonInventory/rest/person'
		});
		
		var UserList = Backbone.View.extend({
			el: '.page',
			render: function(){
				var that = this;
				var users = new Users();				
				users.fetch({
					success: function() {
						//console.log(users.models[0].attributes);
						var template = _.template($('#user-list-template').html(), {users: users.models});
						that.$el.html(template);
					}
				});
			}
		});
		
		var SaveUser = Backbone.View.extend({
			el: '.page',
			render: function() {
				var that = this;
				var template = _.template($('#save-list-template').html(), {user:null});
					that.$el.html(template);
			},
			events: {
				'submit .edit-user-form' : 'saveUser'				
			},
			saveUser: function (ev) {
				var userDetails = $(ev.currentTarget).serializeObject();
				var user = new User();
				user.save(userDetails, {
					success: function(user){
						router.navigate('', {trigger: true});
					}, 
					error: function(user, response){
						console.log(response.status);
					}
				});
				//console.log(userDetails);
				return false;
			}
		});
		
		var EditUser = Backbone.View.extend({
			el: '.page',
			render: function(options) {
				var that = this;
				if(options.id) {
					var user = new User({id:options.id});
					user.fetch({
						success: function() {
							var template = _.template($('#save-list-template').html(), {user: user});
							that.$el.html(template);
						}
					});
				}
			},
			events: {
				'submit .edit-user-form' : 'updateUser'
			},
			updateUser: function (ev) {
				var userDetails = $(ev.currentTarget).serializeObject();
				var user = new User();
				user.update(userDetails, {
					success: function(user){
						router.navigate('', {trigger: true});
					}, 
					error: function(user, response){
						console.log(response.status);
					}
				});
				//console.log(userDetails);
				return false;
			}
		});
		
		var DeleteUser = Backbone.View.extend({
			el: '.page',
			render: function(options) {
				var that = this;
				if(options.id) {
					var user = new User({id:options.id});
					user.destroy({
						success: function(user){
							router.navigate('', {trigger: true});
						}, 
						error: function(user, response){
							console.log(response.status);
						}
					});
				}
			}
		});
		
		var Router = Backbone.Router.extend({
			routes: {
				'': 'home',
				'new': 'saveUser',
				'edit/:id' : 'editUser' ,
				'delete/:id' : 'deleteUser'
			}
		});
		
		var userList = new UserList();
		var saveUser = new SaveUser();
		var editUser = new EditUser();
		var deleteUser = new DeleteUser();
		
		var router = new Router();
		router.on('route:home', function(){
			//console.log('We have loaded the home page');
			userList.render();
		});
		router.on('route:saveUser', function(){
			//console.log('show user form');
			saveUser.render();
		});
		router.on('route:editUser', function(id) {
			//console.log('show edit form');
			editUser.render({id: id});
		});
		router.on('route:deleteUser', function(id) {
			//console.log('show delete form');
			deleteUser.render({id: id});
		});
		Backbone.history.start();
	</script>
</body>
</html>